package com.oauth.exception;

import com.oauth.error.ErrorModel;
import io.swagger.annotations.ResponseHeader;
import org.apache.log4j.Logger;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthRuntimeException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import java.util.Date;

/**
 * 异常处理
 * Created by yangjianbo on 2016/9/27.
 */
@ControllerAdvice
public class HandlException {

    private Logger logger =  Logger.getLogger(HandlException.class);

    @ExceptionHandler(OAuthProblemException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorModel deal(OAuthProblemException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************OAuthProblemException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
        return new ErrorModel(ex.getError(),ex.getDescription());
    }

    @ExceptionHandler(OAuthRuntimeException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String deal(OAuthRuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************OAuthRuntimeException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
        return ex.getMessage();
    }

    @ExceptionHandler(OAuthSystemException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String deal(OAuthSystemException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************OAuthSystemException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
        return ex.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String deal(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************RuntimeException ------ 未处理异常--请联系开发人员（" + new Date().toString()+ "） ------- ***********");
        return "出现未授检测异常，请联系开发人员，提高系统稳定性";
    }
}
